<template>
  <div class="inventory-manage">
    <div class="header">
      <el-button type="primary" @click="showRecordDialog('in')">入库</el-button>
      <el-button type="warning" @click="showRecordDialog('out')">出库</el-button>
      <el-button type="info" @click="showRecordDialog('check')">盘点</el-button>
      
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="输入商品名称搜索"
          class="search-input"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="库存列表" name="stock">
        <el-table :data="stockList" border>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="商品名称"></el-table-column>
<!--          <el-table-column prop="categoryName" label="分类"></el-table-column>-->
          <el-table-column prop="quantity" label="当前库存"></el-table-column>
          <el-table-column label="库存状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStockStatusType(scope.row.quantity)">
                {{ getStockStatusText(scope.row.quantity) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <el-tab-pane label="出入库记录" name="record">
        <el-table :data="recordList" border>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="type" label="类型" width="100">
            <template slot-scope="scope">
              <el-tag :type="getRecordTypeTag(scope.row.type)">
                {{ getRecordTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column prop="operatorName" label="操作人"></el-table-column>
          <el-table-column prop="createdAt" label="操作时间"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 出入库对话框 -->
    <el-dialog :title="recordDialogTitle" :visible.sync="recordDialogVisible">
      <el-form :model="recordForm" :rules="recordRules" ref="recordForm" label-width="100px">
        <el-form-item label="商品" prop="productId">
          <el-select v-model="recordForm.productId" filterable placeholder="请选择商品">
            <el-option
                v-for="item in stockList"
                :key="item.id"
                :label="`${item.name} (库存: ${item.quantity})`"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="recordForm.quantity" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="recordForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="recordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRecordSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStockListByName,getStockList, getStockRecordList, saveInventoryRecord } from '@/api/inventory.js'
// import { getProductOptions } from '@/api/product.js'

export default {
  name: 'InventoryManage',
  data() {
    return {
      activeTab: 'quantity',
      searchQuery: '',
      stockList: [],
      recordList: [],
      productOptions: [],
      recordDialogVisible: false,
      recordDialogTitle: '',
      recordForm: {
        productId: '',
        quantity: 1,
        // name: '',
        type: 1,
        remark: ''
      },
      recordRules: {
        productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getStockList()
    this.getStockRecordList()
  },
  // watch: {
  //   'recordForm.productId': function (newVal) {
  //     const selectedProduct = this.stockList.find(item => item.id === newVal);
  //     if (selectedProduct) {
  //       this.recordForm.name = selectedProduct.name; // 更新商品名称
  //     } else {
  //       this.recordForm.name = ''; // 如果未选择商品，清空名称
  //     }
  //   }
  // }，
  methods: {
    async getStockList() {
      try {
        const { data } = await getStockList(this.searchQuery)
        console.log(data)
        this.stockList = data
      } catch (error) {
        this.$message.success('获取库存列表成功')
      }
    },
    async getStockRecordList() {
      try {
        const { data } = await getStockRecordList(this.searchQuery)
        console.log(data)
        this.recordList = data
      } catch (error) {
        this.$message.success('获取库存记录列表成功')
      }
    },
    // async getRecordList() {
    //   try {
    //     const { data } = await getInventoryRecords()
    //     this.recordList = data
    //   } catch (error) {
    //     this.$message.success('获取记录列表成功')
    //   }
    // },
    // async getProductOptions() {
    //   try {
    //     const { data } = await getProductOptions()
    //     this.productOptions = data
    //   } catch (error) {
    //     this.$message.error('获取商品列表失败')
    //   }
    // },
    handleTabClick() {
      if (this.activeTab === 'record') {
        this.getStockRecordList()
      }
    },
    async handleSearch() {
      console.log("this.searchQuery", this.searchQuery);
      if (!this.searchQuery.trim()) {
        this.$message.warning('请输入商品名称进行搜索');
        return;
      }
      try {
        const response = await getStockListByName({name:this.searchQuery});
        console.log("response", response)
        if (response.code === 200) {
          this.stockList = response.data.inventory;
          this.recordList = response.data.records;
          console.log("库存列表", this.stockList);
          console.log("出入库记录", this.recordList);
        } else {
          this.$message.error('搜索失败: ' + response.message);
        }
      } catch (error) {
        this.$message.error('搜索失败，请稍后再试');
        console.error(error);
      }
    },
    showRecordDialog(type) {
      this.recordForm = {
        productId: '',
        quantity: 1,
        type: type === 'in' ? 1 : type === 'out' ? 2 : 3,
        remark: ''
      }
      this.recordDialogTitle = type === 'in' ? '入库' : type === 'out' ? '出库' : '盘点'
      this.recordDialogVisible = true
      this.getStockList()
      this.getStockRecordList()
    },
    async handleRecordSubmit() {
      this.$refs.recordForm.validate(async valid => {
        if (valid) {
          try {
            await saveInventoryRecord(this.recordForm)
            this.$message.success('操作成功')
            this.recordDialogVisible = false
            this.getStockList()
            if (this.activeTab === 'record') {
              this.getRecordList()
            }
          } catch (error) {
            this.$message.error('操作失败')
          }
        }
      })
    },
    getStockStatusType(stock) {
      if (stock <= 0) return 'danger'
      if (stock < 10) return 'warning'
      return 'success'
    },
    getStockStatusText(stock) {
      if (stock <= 0) return '缺货'
      if (stock < 10) return '低库存'
      return '正常'
    },
    getRecordTypeTag(type) {
      return type === 1 ? 'success' : type === 2 ? 'warning' : 'info'
    },
    getRecordTypeText(type) {
      return type === 1 ? '入库' : type === 2 ? '出库' : '盘点'
    }
  }
}
</script>

<style scoped>
.inventory-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.search-area {
  display: flex;
  align-items: center;
}
.search-input {
  width: 300px;
  margin-left: 20px;
}
</style> 